package com.app.studyroom;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.app.studyroom.api.ApiClient;
import com.app.studyroom.api.ApiResponse;
import com.app.studyroom.api.ApiService;
import com.app.studyroom.api.model.ssrUser.IsUserBindResponse;
import com.app.studyroom.api.model.ssrUser.LoginRequest;
import com.app.studyroom.db.UserInfo;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AccountLoginActivity extends BaseActivity {

    private EditText editID, editPassword;
    private Button btnLogin;
    private TextView tvRegister;
    private String identity = "user"; // 默认身份
    private ImageView image_back;
    private LinearLayout layout_register_hide;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account_login);

        //此处的identity来源于选择用户登录还是管理员登录  故只有两种身份 管理员和用户  user和admin
        identity = getIntent().getStringExtra("identity");
        if (identity == null) identity = "user";

        editID = findViewById(R.id.editID);
        editPassword = findViewById(R.id.editPassword);
        btnLogin = findViewById(R.id.btnLogin);
        tvRegister = findViewById(R.id.tv_Register);
        image_back = findViewById(R.id.ic_back);
        layout_register_hide = findViewById(R.id.layout_register_hide);

        if(identity.equals("user")) {
            //
        }else if(identity.equals("admin")){
            //管理员隐藏注册接口
            layout_register_hide.setVisibility(View.GONE);
        }

        btnLogin.setOnClickListener(v -> handleLogin());
        tvRegister.setOnClickListener(v -> {
            Intent intent = new Intent(this, AccountRegisterActivity.class);
            startActivity(intent);
            overridePendingTransition(0, 0);
            finish();
        });

        image_back.setOnClickListener(v -> onBackPressed());
    }

    private void handleLogin() {
        String idCard = editID.getText().toString().trim();
        String password = editPassword.getText().toString().trim();

        if (idCard.isEmpty() || password.isEmpty()) {
            Toast.makeText(this, "请输入证件号和密码", Toast.LENGTH_SHORT).show();
            return;
        }

        LoginRequest request = new LoginRequest(idCard, password);
        ApiService apiService = ApiClient.getClient().create(ApiService.class);

        Call<ApiResponse<UserInfo>> call = apiService.login(request);

        call.enqueue(new Callback<ApiResponse<UserInfo>>() {
            @Override
            public void onResponse(Call<ApiResponse<UserInfo>> call, Response<ApiResponse<UserInfo>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    ApiResponse<UserInfo> resp = response.body();

                    // ✅ 改为更严谨的判断逻辑
                    if (resp.getCode() == 200 && resp.getData() != null) {
                        UserInfo user = resp.getData();
                        String userBs = user.getUserBs();
                        boolean isLoginAllowed = false;

                        if ("user".equals(identity) && "用户".equals(userBs)) {
                            isLoginAllowed = true;
                        } else if ("admin".equals(identity) &&
                                ("区域管理员".equals(userBs) || "超级管理员".equals(userBs))) {
                            isLoginAllowed = true;
                        }

                        if (isLoginAllowed) {
                            saveLoginInfo(user, resp.getToken());
                            Toast.makeText(AccountLoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();

                            if ("admin".equals(identity)) {
                                startActivity(new Intent(AccountLoginActivity.this, AdminDashboardActivity.class));
                            } else {
                                startActivity(new Intent(AccountLoginActivity.this, PersonalCenterActivity.class));
                            }
                            finish();
                        } else {
                            Toast.makeText(AccountLoginActivity.this, "登录失败：权限不符合", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        // ✅ 登录失败，提示原因
                        Toast.makeText(AccountLoginActivity.this,
                                "登录失败：" + (resp.getMessage() != null ? resp.getMessage() : "未知错误"),
                                Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(AccountLoginActivity.this, "服务器异常", Toast.LENGTH_SHORT).show();
                }
            }


            @Override
            public void onFailure(Call<ApiResponse<UserInfo>> call, Throwable t) {
                Toast.makeText(AccountLoginActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });


    }

    //加绑定后的session
    private void saveLoginInfo(UserInfo user, String token) {
        SharedPreferences sp = getSharedPreferences("Session", MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();

        editor.putString("token", token);
        editor.putLong("userId", user.getId());
        editor.putString("userName", user.getUserName());
        //Log.d("LoginInfo", "userName = " + user.getUserName());
        editor.putString("userZjh", user.getUserZjh());
        editor.putString("userSjh", user.getUserSjh());
        editor.putString("userNumber", user.getUserNumber());
        editor.putString("userBs", user.getUserBs());
        editor.putString("qy", user.getQy());
        editor.putString("identity", user.getUserBs()); //保存的identity用于区分超级管理员、区域管理员、用户
        editor.putString("userImage",user.getUserImage());
        editor.putString("studyTime",user.getStudyTime());//学习时长
        //Log.d("LoginInfo", "userImage = " + user.getUserImage());
        editor.apply();

        // 接着调用是否绑定座位接口
        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        apiService.isUserBind(token).enqueue(new Callback<ApiResponse<IsUserBindResponse>>() {
            @Override
            public void onResponse(Call<ApiResponse<IsUserBindResponse>> call, Response<ApiResponse<IsUserBindResponse>> response) {
                if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                    IsUserBindResponse bindInfo = response.body().getData();

                    // ✅ 打印完整返回值
                    Log.d("BindCheck", "返回值 bind = " + bindInfo.isBind());
                    Log.d("BindCheck", "seatPlace = " + bindInfo.getSeatPlace());
                    Log.d("BindCheck", "seatNum = " + bindInfo.getSeatNum());

                    SharedPreferences.Editor bindEditor = getSharedPreferences("Session", MODE_PRIVATE).edit();
                    bindEditor.putBoolean("isBind", bindInfo.isBind());
                    bindEditor.putString("bindSeatPlace", bindInfo.getSeatPlace());
                    bindEditor.putString("bindSeatNum", bindInfo.getSeatNum());
                    bindEditor.apply();
                } else {
                    Log.w("BindCheck", "接口调用失败或无数据：" + (response.body() != null ? response.body().getMessage() : "空响应体"));
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<IsUserBindResponse>> call, Throwable t) {
                Log.e("BindCheck", "网络请求失败：" + t.getMessage());
            }
        });



    }
    public static class AdminApprovalTaskActivity {
    }
}
